import os
import subprocess as sub
from wsgiref.simple_server import make_server

from monitor_lib import cpu, ram, hd


def app(env, callback):
    status = '200 OK'
    path = env['PATH_INFO']
    if path == '/monitor/cpu':      # 显示CPU信息
        text = cpu()
    elif path == '/monitor/ram':    # 显示RAM信息
        text = ram()
    elif path == '/monitor/hd':     # 显示HD信息
        text = hd()
    elif path == '/monitor':     # 显示HD信息
        text1 = cpu()
        text2 = ram()
        text3 = hd()
        text = '%s\n%s\n%s' % (text1, text2, text3)
    else:                           # 返回404错误
        status = '404 NOT FOUND'
        text = 'NOT FOUND'

    response_data = text.encode()
    response_headers = [
        ('Content-Type', 'text/plain'),
        ('Content-Length', str(len(response_data)))
    ]

    callback(status, response_headers)
    return [response_data]


if __name__ == '__main__':
    host = 'localhost'
    port = 8000
    print('serving on %s:%s' % (host, port))
    httpd = make_server(host, port, app)
    httpd.serve_forever()
